//
//  ThirdAPI.swift
//  jiuzhoudai
//
//  Created by zhaochengfeng on 2025/7/9.
//

import Foundation
import Moya
import CryptoKit
import SwiftyJSON
import Alamofire

// 定义 API 请求的 Target
enum JQFXHMoliffAPI {
    case jqfxhMoliSendggMsg(mobile: String)
    case jqfxhMolirrLogin(mobile: String, code:String)
    case jqfxhCityssList
    case jqfxhLoanmApply(dic: [String: String])
    case jqfxhGetttProtocols(code: String, form_id: String, product_id: String)
    case jqfxhCuuonfirm(stepId: String, productId: String)
}

// 实现 Moya 的 TargetType 协议
extension JQFXHMoliffAPI: TargetType {
    
    private var appkey : String {"Eg2qIe1GS8y6wdhu"}
    private var appSecret : String {"giepPHXGjWK6MQYI"}
    var baseURL: URL {
        return URL(string: "https://hyj.mlffgg.cn")!

    }
    
   
    
    var parameterEncoder: any ParameterEncoder {
        return URLEncodedFormParameterEncoder.default
    }
    
    var encoding: ParameterEncoding {
        return URLEncoding.default
    }
    
    var multipartBody: [Moya.MultipartFormData] {
        
        return self.params.map { key, value in
            Moya.MultipartFormData(provider: .data(String(describing: value).data(using: .utf8)!),
                              name: key)
        }
    }
    
    var path: String {
        switch self {
        case .jqfxhMoliSendggMsg(_):
            return "/hyj/code/loginCode.html"
        case .jqfxhMolirrLogin(_, _):
            return "/hyj/user/codeLogin.html"
        case .jqfxhCityssList:
            return "/hyj/user/cityTreeV1.html"
        case .jqfxhLoanmApply(_):
            return "/hyj/user/submit.html"
        case .jqfxhGetttProtocols(_, _, _):
            return "/hyj/user/protocol.html"
        case .jqfxhCuuonfirm(_, _):
            return "/hyj/user/confirm.html"
        }
    }
    
    var method: Moya.Method {
        return .post

    }
    
    var task: Task {
        .uploadMultipart(multipartBody)
    }

    
    func md5(_ string: String) -> String {
        let digest = Insecure.MD5.hash(data: string.data(using: .utf8) ?? Data())
        return digest.map { String(format: "%02hhx", $0) }.joined()
    }
    
    
    var headers: [String: String]? {
        return [
            "Content-Type": "multipart/form-data"
        ]
    }
    
    func jqfxhGetSignttPara(para:Dictionary<String, Any>) -> Dictionary<String, Any> {
        var params = para
        var strings: [String] = []
        params.keys.sorted().forEach { key in
            if let value = params[key] {
                if let valueStr = value as? String {
                    strings.append(key + "=" + valueStr)
                }
            }
        }
        
        let longvvString = strings.joined(separator: "&") + appSecret
        params["sign"] = self.md5(longvvString)
        return params
    }
    
    
}



extension JQFXHMoliffAPI: JQFXHThirdErrorqqParams {
    var params : [String: Any] {
        let params: [String: Any]
        switch self {
        case .jqfxhMoliSendggMsg(let mobile):
            let raw = ["mobile": mobile,
                       "app_key": appkey]
            params = jqfxhGetSignttPara(para: raw)
        case .jqfxhMolirrLogin(let mobile, let code):
            let raw = ["mobile": mobile,
                       "sms_code": code,
                       "app_key": appkey]
            params = jqfxhGetSignttPara(para: raw)
        case .jqfxhCityssList:
            let raw = ["app_key": appkey]
            params = jqfxhGetSignttPara(para: raw)
        case .jqfxhLoanmApply(let dic):
            var raw = ["app_key": appkey, "assistant_key": "template_h5_12"] as [String : Any]
            if let user = JQFXHNetworkManager.shared.jqfxhCurrentUser, !user.access_token.isEmpty {
                raw["base_access_token"] = user.access_token
            }
            let merged = raw.merging(dic) { (_, new) in new }

            params = jqfxhGetSignttPara(para: merged)
        case .jqfxhGetttProtocols(code: let code, form_id: let formId, product_id: let productId):
            let raw = ["code": code, "form_id": formId, "product_id": productId]
            params = jqfxhGetSignttPara(para: raw)
        case .jqfxhCuuonfirm(stepId: let stepId, productId: let productId):
            var raw = ["step_id": stepId, "match_type": "2", "id": productId, "app_key": appkey]
            if let user = JQFXHNetworkManager.shared.jqfxhCurrentUser, !user.access_token.isEmpty {
                raw["base_access_token"] = user.access_token
            }
            params = jqfxhGetSignttPara(para: raw)
        }
        return params
    }
    
    func mobile() -> String {
        return self.params["mobile"] as? String ?? ""
    }
    
    func jqfxhErrorrrCode(json: JSON) -> Int {
        json["status"].intValue
    }
    
    func jqfxhIsqqError(json: JSON) -> Bool {
        jqfxhErrorrrCode(json: json) != 1
    }
    
    func jqfxhErrorssMsg(json: JSON) -> String {
        json["info"].stringValue
    }
    
    
}
